//
//  WPComposeTypeView.swift
//  WB
//
//  Created by 汪鹏 on 2017/1/16.
//  Copyright © 2017年 汪鹏. All rights reserved.
//

import UIKit
import pop

// 最大列数
private let maxCol:CGFloat = 6
// 最大行数
private let maxRow:CGFloat = 2

private let WidthAndHeight:CGFloat = 100

private let Screen_W = UIScreen.main.bounds.width

class WPComposeTypeView: UIView {

    // scrollView
    @IBOutlet weak var contentView: UIScrollView!
    
    // 关闭按钮
    @IBOutlet weak var deleteButton: UIButton!
    
    // 返回按钮
    @IBOutlet weak var backButton: UIButton!
    
    // 删除按钮的centerX
    @IBOutlet weak var deleteButtonCenterXcons: NSLayoutConstraint!
    
    // 返回按钮的centerX
    @IBOutlet weak var backButtonCenterXCons: NSLayoutConstraint!
    
    // 动画结束modal控制器
    var presentViewControllerBlock:((_ className: String) -> ())?
    
    override func awakeFromNib() {
        
       setupUI()
        
    }
    
    
    ///  设置界面
    private func setupUI() {
        
        let image_normals = ["compose_pic_add","compose_add_background","compose_camerabutton_background","compose_emoticonbutton_background","compose_keyboardbutton_background","compose_mentionbutton_background","compose_toolbar_picture","compose_trendbutton_background","compose_pic_add","compose_add_background","compose_camerabutton_background"]
        
        let image_highliteds = ["compose_pic_add_highlighted","compose_add_background_highlighted","compose_camerabutton_background_highlighted","compose_emoticonbutton_background_highlighted","compose_keyboardbutton_background_highlighted","compose_mentionbutton_background_highlighted","compose_toolbar_picture_highlighted","compose_trendbutton_background_highlighted","compose_pic_add_highlighted","compose_add_background_highlighted","compose_camerabutton_background_highlighted"]
        
        let classNames = ["WPViewController","11111","11111","11111","11111","11111","11111","11111","","11111","11111"];
        
        let button_tags = [1111,2222,3333,4444,5555,6666,7777,8888,9999,0000,11111]
        
        let contentViewH = contentView.bounds.height
        
        for i in 0..<image_normals.count {
            
            let image_normal = image_normals[i]
            
            let image_highlited = image_highliteds[i]
            
            let button = WPComposeTypeButton.composeButton(image: image_normal, highlightImage: image_highlited)
            
            button.tag = button_tags[i]
            
            button.className = classNames[i]
            
            let row = i/Int(maxCol)
            
            let col = i%Int(maxCol)
            
            let marginH = (2 * Screen_W - maxCol * WidthAndHeight) / (maxCol + 2)
            
            let marginV = (contentViewH - maxRow * WidthAndHeight) / (maxRow + 1)
            
            var x = marginH + (WidthAndHeight + marginH)*CGFloat(col)
            
            if i >= 3 && i < 6  || i > 8 {
                
                x += marginH
            }
            
            let y = marginV + (WidthAndHeight + marginV)*CGFloat(row)
            
            button.frame = CGRect(x: x, y: y, width: WidthAndHeight, height: WidthAndHeight)
            
            contentView.addSubview(button)
            
            button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
            
        }
        
        contentView.contentSize = CGSize(width: 2 * Screen_W, height: contentView.bounds.height)
        
        contentView.isPagingEnabled = true
        
        contentView.isScrollEnabled = false
        
    }
    
    
    /// item的点击事件
    @objc private func buttonClick(button:WPComposeTypeButton){
    
        switch button.tag {
            
        case 9999: // 处理更多按钮的点击
            
            let buttonMoveX = Screen_W / 6
            
            backButtonCenterXCons.constant = -buttonMoveX
            
            deleteButtonCenterXcons.constant = buttonMoveX
            
            backButton.isHidden = false
            
            UIView.animate(withDuration: 0.25, animations: { 
                
                self.contentView.contentOffset = CGPoint(x: Screen_W, y: 0)
                
                self.layoutIfNeeded()
            })
            
        default:
            // 点击按钮的动画
            scaleButtonXY(ComposeTypeButton: button)
            
        }
        
    }
    
    /// 关闭按钮的点击事件
    @IBAction func deleteButtonClick(_ sender: Any) {
        
        deleteButtonSpringAnimate()
        
    }
    /// 返回按钮的点击事件
    @IBAction func backPrePage(_ sender: Any) {
        
        backButtonCenterXCons.constant = 0
        
        deleteButtonCenterXcons.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: {
            
            self.contentView.contentOffset = CGPoint(x:0, y: 0)
            
            self.layoutIfNeeded()
            
        }) { (_) in
            
            self.backButton.isHidden = true
        }
        
    }
    /// 创建视图
    class func composeView() -> WPComposeTypeView {
       
        let nib = UINib(nibName: "WPComposeTypeView", bundle: nil)
        
        let composeView = nib.instantiate(withOwner: nil, options: nil)[0] as! WPComposeTypeView
        
        composeView.frame = CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: UIScreen.cz_screenHeight())
        
        return composeView
        
    }
    
    // 显示
    func show(block:@escaping (_ className: String) -> ()) {
        
        presentViewControllerBlock = block

        let rootVC = UIApplication.shared.keyWindow?.rootViewController as? WPMainViewController
        
        rootVC?.view.addSubview(self)
        
        // 开始动画
        showAnimate()

    }

}

private extension WPComposeTypeView {
    
    // 点击按钮的动画
    func scaleButtonXY(ComposeTypeButton:WPComposeTypeButton) {
        
        for (i,button) in contentView.subviews.enumerated() {
            
            if button.isMember(of: WPComposeTypeButton.self) { // 判断是不是某个类
             
            let btn = button as! WPComposeTypeButton
            // 缩放
            let ScaleAnimate:POPBasicAnimation = POPBasicAnimation(propertyNamed:kPOPViewScaleXY)
            
            let scale = btn == ComposeTypeButton ? 1.5 : 0.4
                
            ScaleAnimate.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            
            ScaleAnimate.duration = 0.5
            
            btn.pop_add(ScaleAnimate, forKey: nil)
            
            // 透明度动画
            let alphaAnimate:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            
            alphaAnimate.toValue = 0.2
            
            alphaAnimate.duration = 0.5
            
            btn.pop_add(alphaAnimate, forKey: nil)
            
            if i == contentView.subviews.count-3 {
                
                alphaAnimate.completionBlock = {[unowned self](_,_) in
                    // 弹出控制器
                    self.presentViewControllerBlock?(ComposeTypeButton.className!)
                    }
                }
            }
        }
    }
    
    // 透明度变化显示动画
    func showAnimate() {
        
        let animate:POPBasicAnimation = POPBasicAnimation(propertyNamed:kPOPViewAlpha)
        
        animate.fromValue = 0
        
        animate.toValue = 1
        
        animate.duration = 0.25
        
        pop_add(animate, forKey: nil)
        
        showSpringAnimate()
    }
    
    // 透明度变化隐藏动画
    func hideAnimate() {
        
        let animate:POPBasicAnimation = POPBasicAnimation(propertyNamed:kPOPViewAlpha)
        
        animate.fromValue = 1
        
        animate.toValue = 0
        
        animate.duration = 0.25
        
        pop_add(animate, forKey: nil)
        
        // 移除当前视图
        removeFromSuperview()
        
    }
    

    
    // 按钮显示的弹力动画
    func showSpringAnimate() {
       
        for (i,btn) in contentView.subviews.enumerated() {
        
            let animate:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
        
            animate.fromValue = btn.center.y + 300
            
            animate.toValue = btn.center.y
            
            animate.springSpeed = 10
            
            animate.springBounciness = 8
            
            animate.beginTime = CACurrentMediaTime() + CFTimeInterval(i)*0.025
            
            btn.pop_add(animate, forKey: nil)
            
        }
    }
    
    // 按钮下落的弹力动画
    func deleteButtonSpringAnimate() {
        
        for (i,btn) in contentView.subviews.reversed().enumerated() {
            
            let animate:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            animate.fromValue = btn.center.y
            
            animate.toValue = btn.center.y + 400
            
            animate.springSpeed = 10
            
            animate.springBounciness = 8
            
            animate.beginTime = CACurrentMediaTime() + CFTimeInterval(i)*0.025
            
            btn.layer.pop_add(animate, forKey: nil)
            
            // 动画完成
            animate.completionBlock = { (_,_) in
                
               self.hideAnimate()
            }
            
        }
    
    }

}
